package com.java.frontweb.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.java.base.httpclient.HttpResult;
import com.java.base.service.HttpAPIService;
import com.java.frontweb.pojo.Order;
import com.java.frontweb.pojo.User;
import com.java.frontweb.thred.UserThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @ClassName OrderService
 * @Description 订单服务层
 * @Author Trigger Wu
 * @Date 2018/9/231:01
 * @Version 1.0
 **/
@Service
public class OrderService {
    @Autowired
    private HttpAPIService apiService;
    @Value("${CQZG_ORDER_URL}")
    private  String CQZG_ORDER_URL;


    private static final ObjectMapper MAPPER = new ObjectMapper();
    /*
     * the form order submit by id
     *
     * @author Tigger Wu
     * @date 2018/9/23 1:02
     * @param []
     * @return java.lang.String
     */
    public String submit(Order order) throws IOException {
        String url =CQZG_ORDER_URL +"/rest/order/create";
        //拿到用户信息
        User user = UserThreadLocal.get();
        order.setBuyerNick(user.getUsername());
        order.setUserId(user.getId());
        try {
            String json = MAPPER.writeValueAsString(order);
            HttpResult httpResult = apiService.doPostJson(url, json);
            //判断状态码是否是成功 200
            if(httpResult.getCode().intValue() ==200){
                //判断返回业务状态码 200          跟状态码有区别
                String body = httpResult.getBody();
                JsonNode jsonNode = MAPPER.readTree(body);
                if(jsonNode.get("status").asInt() == 200){
                    //提交成功
                    return jsonNode.get("data").asText();
                }

            }
        }catch (Exception e){
              e.printStackTrace();
        }
        return null;
    }
    /*
     *  查询订单信息
     *
     * @author Tigger Wu
     * @date 2018/9/25  | 10:13
     * @param [orderId]
     * @return Order
     */
    public Order queryByOrderId(String orderId) {
        String url = CQZG_ORDER_URL + "/rest/order/query/" + orderId;
        try {
            String jsonData = this.apiService.doGet(url);
            if (StringUtils.isNotEmpty(jsonData)) {
                return MAPPER.readValue(jsonData, Order.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
